package com.zcg.blogger.web.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.hibernate.validator.constraints.Email;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.test.annotation.ExpectedException;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zcg.blogger.dao.ConfigDao;
import com.zcg.blogger.exception.UserException;
import com.zcg.blogger.model.User;
import com.zcg.blogger.service.ConfigService;
import com.zcg.blogger.service.UserService;
import com.zcg.blogger.util.PattemUtil;

/**
 * 用户控制器
 * 
 * @author zcg
 *
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Resource
	private UserService userService;

	@Resource
	private ConfigService configService;

	/**
	 * 根据name取得配置属性
	 * 
	 * @param name
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{name}/config", method = RequestMethod.GET)
	public String config(@PathVariable String name, Model model) {
		String attribute = configService.getAttribute(name);
		model.addAttribute("attribute", attribute);
		System.out.println(attribute);
		return "user/config";
	}

	/**
	 * 展示用户
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/showUser")
	public String toIndex(HttpServletRequest request, Model model) {
		int UserId = Integer.parseInt(request.getParameter("id"));
		User user = userService.getUserById(UserId);
		model.addAttribute("user", user);
		return "hello";
	}

	/**
	 * 登录
	 * 
	 * @param user
	 * @param br
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(@Validated User user, BindingResult br,
			HttpSession session, Model model) {
		if (br.hasErrors()) {
			return "user/login";
		}
		if (!userService.loadByName(user.getUsername())) {
			model.addAttribute("error", "该用户名不存在");
			return "user/login";
		}
		user = userService.check(user.getUsername(), user.getPassword());
		if (user == null) {
			model.addAttribute("error", "用户名/密码不正确");
			return "user/login";
		}
		session.setAttribute("loginUser", user);
		return "redirect:/";
	}

	/**
	 * 退出
	 * 
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session) throws Exception {
		session.removeAttribute("loginUser");
		return "redirect:/";

	}

	/**
	 * 登录用户页面
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(@ModelAttribute("user") User user) {
		return "user/login";
	}

	/**
	 * 注册用户页面
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public String register(@ModelAttribute("user") User user) {
		return "user/register";
	}

	/**
	 * 注册用户
	 * 
	 * @param user
	 * @param br
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(@Validated User user, BindingResult br,
			HttpSession session) {
		if (br.hasErrors()) {
			// 如果有错误返回add页面
			return "user/register";
		}
		userService.add(user);
		session.setAttribute("loginUser", user);
		return "redirect:../article/";
	}

	/**
	 * 找回密码页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/findPassword", method = RequestMethod.GET)
	public String findPassword() {
		return "user/findPassword";
	}

	/**
	 * 找回密码请求
	 * 
	 * @param email
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/findPassword", method = RequestMethod.POST)
	public String findPassword(String email, HttpServletRequest req)
			throws Exception {
		userService.sendEmail(email);
		return "user/findPasswordSuccess";
	}

	/**
	 * 打开更新密码页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/updatePassword/{email}", method = RequestMethod.GET)
	public String updatePassword(@PathVariable String email) {
		return "user/updatePassword";
	}

	/**
	 * 更新密码请求
	 * 
	 * @param user
	 * @param email
	 * @param password
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
	public String updatePassword(@ModelAttribute("user") User user,
			String email, String password, HttpServletRequest req) {
		userService.updatePassword(email, password);
		return "redirect:login";
	}

	/**
	 * 默认页面
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/")
	public String index(Model model) {
		List<User> users = userService.loadUsers();
		model.addAttribute("users", users);
		return "user/index";
	}

	/**
	 * 用户列表
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/users", method = RequestMethod.GET)
	public String list(Model model) {
		List<User> users = userService.loadUsers();
		model.addAttribute("users", users);
		return "user/list";
	}

	/**
	 * 添加用户页面
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@ModelAttribute("user") User user) {
		return "user/add";
	}

	/**
	 * 增加用户
	 * 
	 * @param user
	 * @param br
	 * @param attachs
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(@Validated User user, BindingResult br,
			@RequestParam("attachs") MultipartFile[] attachs,
			HttpServletRequest req) {
		if (br.hasErrors()) {
			// 如果有错误返回add页面
			return "user/add";
		}
		String realpath = req.getSession().getServletContext()
				.getRealPath("/resources/upload");
		System.out.println(realpath);
		for (MultipartFile attach : attachs) {
			System.out
					.println(attach.getName() + "  size  " + attach.getSize());
			if (attach.isEmpty()) {
				continue;
			}
			File f = new File(realpath + "/" + attach.getOriginalFilename());
			try {
				FileUtils.copyInputStreamToFile(attach.getInputStream(), f);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		userService.add(user);
		// users.put(user.getUsername(), user);
		return "redirect:user/users";
	}

	/**
	 * 展示用户
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public String show(@PathVariable int id, Model model) {
		return show(id, 0, model);
	}

	/**
	 * 展示用户
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}/{operate}", method = RequestMethod.GET)
	public String show(@PathVariable int id, @PathVariable int operate,
			Model model) {
		List<Object> objects = userService.loadObjectsByOperate(id, operate);
		User user = userService.loadById(id);
		model.addAttribute("operate", operate);
		model.addAttribute("objects", objects);
		model.addAttribute(user);
		return "user/show";
	}

	/**
	 * 展示用户
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}/articles", method = RequestMethod.GET)
	public String articles(@PathVariable int id, Model model) {
		User user = userService.loadById(id);
		model.addAttribute(user);
		return "user/articles";
	}

	/**
	 * 展示用户json
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = "json")
	@ResponseBody
	public User show(@PathVariable int id) {
		return userService.loadById(id);
	}

	/**
	 * 更新用户页面
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/{id}/update", method = RequestMethod.GET)
	public String update(@PathVariable int id, Model model) {
		// public String add(Model model){
		User user = userService.loadById(id);
		model.addAttribute(user);
		return "user/update";
	}

	/**
	 * 更新用户
	 * 
	 * @param id
	 * @param user
	 * @param br
	 * @return
	 */
	@RequestMapping(value = "/{id}/update", method = RequestMethod.POST)
	public String update(@PathVariable int id, @Validated User user,
			BindingResult br) {
		if (br.hasErrors()) {
			// 如果有错误返回add页面
			return "user/update";
		}

		userService.update(user);
		return "redirect:../user/users";
	}

	/**
	 * 删除用户
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "{id}/delete", method = RequestMethod.GET)
	public String delete(@PathVariable int id) {
		User user = userService.loadById(id);
		userService.delete(user);
		return "redirect:../users";
	}

	/**
	 * 用户设置信息
	 */
	@RequestMapping(value = "{id}/setting", method = RequestMethod.GET)
	public String setting(@PathVariable int id, Model model) {
		System.out.println(id);
		return setting(id, 0, model);
	}

	/**
	 * 用户设置信息
	 */
	@RequestMapping(value = "{id}/{operate}/setting", method = RequestMethod.GET)
	public String setting(@PathVariable int id, @PathVariable int operate,
			Model model) {
		User user = userService.loadById(id);
		model.addAttribute("operate", operate);
		model.addAttribute("user", user);
		return "user/setting";
	}

	@RequestMapping(value = "/sendCheck", method = RequestMethod.GET)
	public String sendCheckCode(String email) throws Exception {
		if (!PattemUtil.email(email)) {
			throw new UserException("邮箱格式不正确");
		}
		userService.sendCheckCode(email);
		return "true";
	}

	@RequestMapping(value = "updatePassword/old", method = RequestMethod.GET)
	public String updatePassword(int id, String oldPassword,
			String newPassword1, String newPassword2, HttpSession session) {
		session.setAttribute("Change", false);
		if (!newPassword1.equals(newPassword2)) {
			throw new UserException("两次输入密码不匹配");
		}

		if (!userService.getUserById(id).getPassword().equals(oldPassword)) {
			throw new UserException("当前密码不正确");
		}

		userService.updatePassword(oldPassword, newPassword1, id);
		session.setAttribute("Change", true);
		return "redirect:../" + id + "/2/setting";
	}

	@RequestMapping(value = "updateEmail", method = RequestMethod.POST)
	public String updateEmail(int id, String email, String checkCode,
			HttpSession session) {
		session.setAttribute("Change", false);
		if (!checkCode.equals("1234")) {
			checkCode = "1234";
		}

		userService.updateEmail(email, checkCode, id);
		session.setAttribute("Change", true);
		return "redirect:../user/" + id + "/3/setting";
	}

	@RequestMapping(value = "updateAvatar", method = RequestMethod.POST)
	public String updateAvatar(int id,
			@RequestParam("file") MultipartFile file, HttpServletRequest req,
			Model model) {
		String realpath = req.getSession().getServletContext()
				.getRealPath("/resources/images/avatar");
		File f = new File(realpath + "/" + file.getOriginalFilename());
		String avatar = "resources/images/avatar/" +file.getOriginalFilename();
//		System.out.println(avatar);
		if (!f.exists()) {
			f.mkdirs();
		}

		//保存  
        try {  
            file.transferTo(f);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
//        System.out.println(realpath);
        userService.updateAvatar(avatar, id);
		model.addAttribute("fileUrl", realpath + "/" + file.getOriginalFilename());
		return "redirect:../user/" + id + "/1/setting";
	}

}
